package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@Api(tags = "")
@RestController("userDishController")
@RequestMapping("/user/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类获取菜品包含口味列表
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public Result<List> list(Long categoryId) {
        // 缓存优化: 在查询数据库之前先查询缓存
        String key = "dish_" + categoryId;
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);
        // 如果查到结果 直接返回缓存数据
        if (list != null && list.size() > 0) {
            return Result.success(list);
        }

        // 如果没有查询到结果 需要查询数据库
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        list = dishService.listAndFalvorByCategoryId(dish);
        // 将数据库查询出来的数据加入到缓存中
        redisTemplate.opsForValue().set(key, list);

        return Result.success(list);
    }
}
